package com.gree.shyun.util;


import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.Pipeline;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.html.CssAppliers;
import com.itextpdf.tool.xml.html.CssAppliersImpl;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
import org.w3c.tidy.Tidy;

import java.io.*;

import static com.itextpdf.text.Font.NORMAL;

/**
 * html转pdf
 */
public class Html2PdfUtil {

    /**
     * 转化类
     *
     * @param html  html文件输入路径(带文件名称)
     * @param xhtml xhtml文件输入路径(带文件名称)
     * @return
     */
    public static String html2Xhtml(String html, String xhtml) {

        String path = null;
        try {
            FileInputStream fin = new FileInputStream(html);
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            int data = -1;
            while ((data = fin.read()) != -1) {
                byteArrayOut.write(data);
            }
            fin.close();
            byte[] htmlFileData = byteArrayOut.toByteArray();

            byteArrayOut.close();

            ByteArrayInputStream tidyInput = new ByteArrayInputStream(
                    htmlFileData);
            ByteArrayOutputStream tidyOut = new ByteArrayOutputStream();
            Tidy tidy = new Tidy();
            tidy.setInputEncoding("UTF-8");
            tidy.setOutputEncoding("UTF-8");
            tidy.setShowWarnings(false);
            tidy.setIndentContent(true);
            tidy.setSmartIndent(true);
            tidy.setIndentAttributes(false);
            tidy.setMakeClean(true);
            tidy.setQuiet(true);
            tidy.setWord2000(true);
            tidy.setXHTML(true);
            tidy.setErrout(new PrintWriter(System.out));

            tidy.parse(tidyInput, tidyOut);
            tidyInput.close();
            tidyOut.writeTo(new FileOutputStream(xhtml));
            tidyOut.flush();
            tidyOut.close();
            path = xhtml;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            path = null;
        } catch (IOException e) {
            e.printStackTrace();
            path = null;
        }

        return path;
    }

    /**
     * 设置字体信息
     * @return
     */
    private static Font getFontInf() {
        // 字体路径
        String fontPath =FileUtil.getResRootPath()+"font/simheittf.ttf";
        BaseFont baseFont = null;
        Font font = null;
        try {
            // 设置字体路径,字体编码，是否将字体嵌入pdf（默认false）
            baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            // 设置默认字体数据
            font = new Font(baseFont, 12f,Font.NORMAL,BaseColor.BLACK);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return font;
    }

    /**
     * 转PDF
     * @param html
     * @return
     */
    public static String XHtml2Pdf(String html){
        int i = html.lastIndexOf(".html");
        String pdf =  html.substring(0, i) + ".pdf";
        return XHtml2Pdf(html,pdf);
    }
    /**
     * 转化方法
     *
     * @param html html文件输入路径(带文件名称)
     * @param pdf  pdf文件输出路径(带文件名称)
     */
    public static String XHtml2Pdf(String html, String pdf){

        File input = null;
        try {
            int i = html.lastIndexOf(".html");
            String xhtml = null;
            xhtml = html.substring(0, i) + ".xhtml";
            xhtml = html2Xhtml(html, xhtml);

            if (xhtml != null) {
                Document document = new Document();
                PdfWriter writer = PdfWriter.getInstance(document,
                        new FileOutputStream(pdf));
                document.open();
                CssAppliers cssAppliers = new CssAppliersImpl(new FontProvider() {
                    @Override
                    public boolean isRegistered(String s) {
                        return false;
                    }

                    @Override
                    public Font getFont(String s, String s1, boolean b, float v, int i, BaseColor baseColor) {
                        return getFontInf();
                    }
                });
                HtmlPipelineContext htmlContext = new HtmlPipelineContext(
                        cssAppliers);
                htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
                CSSResolver cssResolver = XMLWorkerHelper.getInstance()
                        .getDefaultCssResolver(true);
                Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,
                        new HtmlPipeline(htmlContext, new PdfWriterPipeline(
                                document, writer)));
                XMLWorker worker = new XMLWorker(pipeline, true);
                XMLParser p = new XMLParser(worker);

                input = new File(xhtml);
                FileInputStream inputStream = new FileInputStream(input);
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                p.parse(inputStreamReader);
                document.close();

                inputStream.close();
                inputStreamReader.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return pdf;
    }

    public static void main(String[] args){
        String htmlPath = "D:\\blog\\result.html";
        XHtml2Pdf(htmlPath);
    }

}
